package cn.itcast.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class ResultSetMeteDataTest {
	
	public static void main(String[] args) throws SQLException {
		Map<String, Object> data = read("select * from user where id=1");
		System.out.println(data);
	}
	
	static Map<String, Object> read(String sql) throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int count = rsmd.getColumnCount();
			String[] colNames = new String[count];
			for (int i = 1; i <= count; i++) {
//				System.out.print(rsmd.getColumnClassName(i) + "\t");
//				System.out.print(rsmd.getColumnName(i) + "\t");
//				System.out.println(rsmd.getColumnLabel(i) + "\t");
				colNames[i-1] = rsmd.getColumnLabel(i);
			}
			Map<String, Object> data = null;
			if (rs.next()) {
				data = new HashMap<String, Object>();
				
				for (int i = 0; i < colNames.length; i++) {
					data.put(colNames[i], rs.getObject(colNames[i]));
				}
//				System.out.println(rs.getObject("id") + "\t"
//						+ rs.getObject("name") + "\t"
//						+ rs.getObject("birthday") + "\t"
//						+ rs.getObject("money"));
			}
			return data;
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}

}
